package db;

import base.Intake;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.*;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import utils.DateUtils;

/**
 *
 * @author Shayan
 */
public class IntakeManager {

    private final static String INTAKE_TABLE = "INTAKES";

    public static void deleteAll() throws RecordStoreException {
        RecordStore.deleteRecordStore(INTAKE_TABLE);
    }

    public static void persist(Intake intake)
            throws RecordStoreException, IOException {
        RecordStore rs = RecordStore.openRecordStore(INTAKE_TABLE, true);
        byte[] data = intake.getData();

        int recordId = DatabaseHelper.findRecordId(rs, intake.getId());
        if (recordId == -1) {
            rs.addRecord(data, 0, data.length);
        } else {
            rs.setRecord(recordId, data, 0, data.length);
        }
        rs.closeRecordStore();
    }

    public static Vector getIntakes(String userId, Date from, Date to)
            throws InvalidRecordIDException, RecordStoreNotOpenException, IOException, RecordStoreException {
        RecordStore rs = RecordStore.openRecordStore(INTAKE_TABLE, true);

        Vector result = new Vector();
        long fromTime = from.getTime();
        long toTime = to.getTime();

        RecordEnumeration re = rs.enumerateRecords(null, null, false);
        while (re.hasNextElement()) {
            byte[] data = re.nextRecord();

            ByteArrayInputStream bin = new ByteArrayInputStream(data);
            DataInputStream in = new DataInputStream(bin);

            in.readUTF(); // ignore id
            String dataUserId = in.readUTF();
            if (!dataUserId.equalsIgnoreCase(userId)) {
                continue;
            }
            long dataTime = in.readLong();
            if (dataTime >= fromTime && dataTime < toTime) {
                result.addElement(Intake.create(data));
            }
        }

        rs.closeRecordStore();
        return result;
    }

    public static Vector getDailyIntakes(String userId, Date day)
            throws InvalidRecordIDException, RecordStoreNotOpenException, RecordStoreNotOpenException, IOException, RecordStoreException {
        Date start = DateUtils.getStartOfDay(day);
        Date end = DateUtils.getEndOfDay(day);

        return getIntakes(userId, start, end);
    }
}
